import { getRoleList } from '@/api/org'
import { getWithExpires, setWithExpires } from '@/libs/storage'

export default {
  namespaced: true,
  state: {
    roles: []
  },
  actions: {
    init ({ state, dispatch }) {
      return new Promise(async (resolve) => {
        const url = '/org/roleList'
        const roles = getWithExpires(url)
        if (!roles) {
          const response = await getRoleList({})
          state.roles = response
          setWithExpires(url, response)
        } else {
          state.roles = roles
        }
        
        await dispatch('admin/db/set', {
          dbName: 'role',
          path: 'role.roles',
          value: state.roles,
        }, { root: true })
        
        resolve()
      })
    },
    load ({ state, dispatch }) {
      return new Promise(async resolve => {
        state.roles = await dispatch('admin/db/get', {
          dbName: 'role',
          path: 'role.roles',
          defaultValue: [],
        }, { root: true });
        resolve();
      })
    }
  }
}
